import pandas as pd
from path_name_mapping import get_ad_config
from loguru import logger

# 设置显示所有列（默认只显示部分列）
pd.set_option('display.max_columns', None)

# 设置显示所有行（默认只显示部分行）
pd.set_option('display.max_rows', None)

# 设置列宽（防止内容被截断）
pd.set_option('display.max_colwidth', 100)  # 设置每列最大显示宽度

def get_complete_sheet1(file_path=None):
    df = pd.read_excel(file_path, sheet_name="计划列表", engine='openpyxl')

    # 调试：查看原始数据
    print("原始数据前5行:")
    print(df.head())

    config_df = df.apply(get_ad_config, axis=1, result_type='expand')

    # 调试：查看生成的配置
    print("\n生成的配置前5行:")
    print(config_df.head())

    df = pd.concat([df, config_df], axis=1)

    # 调试：查看合并结果
    print("\n合并后前5行:")
    print(df.head())

    return df

def get_complete_sheet_platform(file_path=None):
    try:
        df = pd.read_excel(file_path, sheet_name="平台精选")
        cols_to_fill = ['人群定向包']
        df[cols_to_fill] = df[cols_to_fill].ffill()
        # print(df['人群定向包'].tolist())
        # print(df['小类'].tolist())
        print(df)
        # print(df['一级选项'].str.split('\n').explode().tolist())
        return df
    except ValueError as e:
        if "Worksheet named '平台精选' not found" in str(e):
            print(f"警告: 文件 {file_path} 中不存在[平台精选]sheet")
            return pd.DataFrame()  # 返回带列名的空DF
        else:
            raise  # 重新抛出其他异常
    except Exception as e:
        print(f"读取文件失败: {e}")
        return pd.DataFrame()

def get_complete_sheet_indus_people(file_path=None):
    """
    读取行业人群sheet，若不存在返回空DataFrame
    """
    try:
        df = pd.read_excel(file_path, sheet_name="行业人群")
        # 处理合并单元格
        cols_to_fill = ['人群定向包', '小类', '一级选项']
        df[cols_to_fill] = df[cols_to_fill].ffill()
        print("成功加载数据:")
        print(df['人群定向包'].tolist())
        print(df.head())
        return df
    except ValueError as e:
        if "Worksheet named '行业人群' not found" in str(e):
            print(f"警告: 文件 {file_path} 中不存在[行业人群]sheet")
            return pd.DataFrame()  # 返回带列名的空DF
        else:
            raise  # 重新抛出其他异常
    except Exception as e:
        print(f"读取文件失败: {e}")
        return pd.DataFrame()
def get_complete_sheet_indus_inters(file_path=None):
    """
    读取行业兴趣sheet，若不存在返回空DataFrame
    """
    try:
        df = pd.read_excel(file_path, sheet_name="行业兴趣")
        # 处理合并单元格
        cols_to_fill = ['人群定向包', '小类', '一级选项']
        df[cols_to_fill] = df[cols_to_fill].ffill()
        print(df)
        return df
    except ValueError as e:
        if "Worksheet named '行业兴趣' not found" in str(e):
            print(f"警告: 文件 {file_path} 中不存在[行业兴趣]sheet")
            return pd.DataFrame()  # 返回空DF
        else:
            raise
    except Exception as e:
        print(f"读取文件失败: {e}")
        return pd.DataFrame()
def get_complete_sheet_keyword(file_path=None):
    """
    读取关键词sheet，若不存在返回空DataFrame
    """
    try:
        df = pd.read_excel(file_path, sheet_name="关键词").dropna(how="all")
        cols_to_fill = ['人群定向包']
        df[cols_to_fill] = df[cols_to_fill].ffill()
        print(df)
        return df
    except ValueError as e:
        if "Worksheet named '关键词' not found" in str(e):
            print(f"警告: 文件 {file_path} 中不存在[关键词]sheet")
            return pd.DataFrame()  # 返回空DF
        else:
            raise
    except Exception as e:
        print(f"读取文件失败: {e}")
        return pd.DataFrame()
def get_complete_sheet_crowd_pack(file_path=None):
    """
    读取关键词sheet，若不存在返回空DataFrame
    """
    try:
        df = pd.read_excel(file_path, sheet_name="人群包")
        print(df)
        return df
    except ValueError as e:
        if "Worksheet named '人群包' not found" in str(e):
            print(f"警告: 文件 {file_path} 中不存在[人群包]sheet")
            return pd.DataFrame()  # 返回空DF
        else:
            raise
    except Exception as e:
        print(f"读取文件失败: {e}")
        return pd.DataFrame()

def get_search_comp(file_path=None):
    """
    读取搜索组件sheet，若不存在返回空DataFrame
    """
    try:
        df = pd.read_excel(file_path, sheet_name="转化组件")
        return df
    except ValueError as e:
        if "Worksheet named '搜索组件' not found" in str(e):
            print(f"警告: 文件 {file_path} 中不存在[搜索组件]sheet")
            return pd.DataFrame()  # 返回空DF
        else:
            raise
    except Exception as e:
        print(f"读取文件失败: {e}")
        return pd.DataFrame()

def get_creative_name(file_path=None):
    """
    读取创意名称组件sheet
    """
    try:
        df = pd.read_excel(file_path, sheet_name="创意名称")
        return df
    except ValueError as e:
        if "Worksheet named '创意名称' not found" in str(e):
            print(f"警告: 文件 {file_path} 中不存在[创意名称]sheet")
            return pd.DataFrame()  # 返回空DF
        else:
            raise
    except Exception as e:
        print(f"读取文件失败: {e}")
        return pd.DataFrame()